package cc.ppay.sso.client.service.impl;

import cc.ppay.sso.client.service.SsoClientService;
import cc.ppay.sso.common.model.CommonResult;
import cc.ppay.sso.common.model.SsoUser;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 客户端业务实现类
 *
 * @author Ade.Xiao 2021/1/30 14:33
 */
public class SsoClientServiceImpl implements SsoClientService {
    private String ssoServer;
    private String logoutPath;
    private String loginCheckPath;

    public SsoClientServiceImpl(String ssoServer) {
        this.ssoServer = ssoServer;
        logoutPath = this.ssoServer.concat("/biz/logout");
        loginCheckPath = this.ssoServer.concat("/biz/loginCheck");
    }

    @Override
    public void logout(String sessionid) {
        if (StrUtil.isNotBlank(sessionid)) {
            Map params = new HashMap<>();
            params.put("sessionid", sessionid);
            HttpUtil.post(logoutPath, params);
        }
    }

    @Override
    public SsoUser loginCheck(String authType, String sessionid) {
        if (StrUtil.isNotBlank(sessionid)) {
            Map params = new HashMap<>();
            params.put("authType", authType);
            params.put("sessionid", sessionid);
            String body = HttpUtil.post(loginCheckPath, params);
            CommonResult result = JSONUtil.toBean(body, CommonResult.class);
            if (result.getSuccess() && !(result.getData() instanceof JSONNull)) {
                return JSONUtil.toBean((JSONObject) result.getData(), SsoUser.class);
            }
        }

        return null;
    }
}
